package org.example.spring_blog.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.example.spring_blog.Constant.Constants;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JWTUtils {

    public static final long Expiration = 30*60*10000;
    private static final String secretStr = "3Gdl10AwP0qu1q0yiWogjuikoiQ79uOZr3A5hmLLVPU=";
    private static final Key key = Keys.hmacShaKeyFor(secretStr.getBytes());


    /**
     * 生成token
     */


    public static String genJwtToken(Map<String,Object> claim){

        claim = new HashMap<>();
        claim.put("id",1);
        claim.put("name","zhangsan");
        String token = Jwts.builder().setClaims(claim)
                .setExpiration(new Date(System.currentTimeMillis() +Expiration))
                .signWith(key) //设置签名
                .compact();
        System.out.println(token);
        return "";
    }


    /**
     * 校验token
     */

    public static Claims parseToken(String token){
        //校验Token
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims = null;
        try {
            claims = build.parseClaimsJws(token).getBody();
        }catch (Exception e){

            log.error("解析token失败, token:{}", token);
            return null;
        }
        return claims;


    }

    public static Integer getIdByToken(String token){
        Claims claims = parseToken(token);
        if (claims!=null){
            Integer userId = (Integer) claims.get(Constants.TOKEN_ID);
            if (userId>0){
                return userId;
            }
        }
        return null;
    }

}
